package sicnu.cs.ich.security.util;

import lombok.val;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author CaiKe
 * @date 2021/12/1 13:18
 */
public class SecurityUtil {
    public static Integer getCurrentUserId() {
        val principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return "anonymousUser".equals(principal) ? -1 : Integer.parseInt(principal);
    }

    public static Authentication getCurrentAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 判断是否存在
     * @param role
     * @return
     */
    public static boolean hasRole(String role){
        var set = AuthorityUtils.authorityListToSet(getCurrentAuthentication().getAuthorities());
        return set.contains("ROLE_"+role);
    }

    /**
     * 判断权限是否存在
     * @param authority 角色信息
     */
    public static boolean hasAuthority(String authority){
        var set = AuthorityUtils.authorityListToSet(getCurrentAuthentication().getAuthorities());
        return set.contains(authority);
    }

}